package cn.jbolt.wechat.common.miniapp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.jbolt.wechat.common.WechatApiResult;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;

public class WechatMaContext {

    public static final WxMaService SERVICE = new WxMaServiceImpl();


    /**
     * 添加配置
     * @param appId
     * @param config
     */
    public static void saveConfig(String appId, WxMaConfig config) {
        SERVICE.addConfig(appId, config);
    }


    /**
     * 移除配置
     * @param appId
     */
    public static void removeConfig(String appId) {
        SERVICE.removeConfig(appId);
    }

    /**
     * 切换到指定配置的小程序
     * @param appId
     */
    public static void switchTo(String appId) {

        SERVICE.switchoverTo(appId);
    }

    /**
     * 切换结束，清空ThreadLocal的appId
     */
    public static void switchOver() {
        WxMaConfigHolder.remove();
    }


    public static WechatApiResult<WxMaJscode2SessionResult> getUserSession(String code) {
        checkAppIdHasSet();
        try {
            WxMaJscode2SessionResult sessionInfo = SERVICE.getUserService().getSessionInfo(code);
            WechatApiResult result = new WechatApiResult();
            result.setData(sessionInfo);
            return result;
        } catch (WxErrorException e) {
            e.printStackTrace();
            return new WechatApiResult<>("获取UserSession失败", e);
        }
    }


    /**
     * 验证用户信息完整性.
     * @param sessionKey
     * @param rawData
     * @param signature
     * @return
     */
    public static boolean checkUserInfo(String sessionKey, String rawData, String signature) {
        checkAppIdHasSet();
        return SERVICE.getUserService().checkUserInfo(sessionKey, rawData, signature);
    }


    /**
     * 解密用户敏感数据.
     * @param sessionKey
     * @param encryptedData
     * @param ivStr
     * @return
     */
    public static WechatApiResult<WxMaUserInfo> getUserInfo(String sessionKey, String encryptedData, String ivStr) {
        checkAppIdHasSet();
        WxMaUserInfo userInfo = SERVICE.getUserService().getUserInfo(sessionKey, encryptedData, ivStr);
        WechatApiResult result = new WechatApiResult();
        result.setData(userInfo);
        return result;
    }

    /**
     * 获取手机号信息
     * @param code
     * @return
     */
    public static WechatApiResult<WxMaPhoneNumberInfo> getPhoneInfo(String code) {
        checkAppIdHasSet();
        try {

            WxMaPhoneNumberInfo phoneNoInfo = SERVICE.getUserService().getPhoneNoInfo(code);
            WechatApiResult result = new WechatApiResult();
            result.setData(phoneNoInfo);
            return result;
        } catch (WxErrorException e) {
            e.printStackTrace();
            return new WechatApiResult("获取手机号信息失败", e);
        }

    }

    /**
     * 验证签名
     * @param timestamp
     * @param nonce
     * @param signature
     * @return
     */
    public static boolean  checkSignature(String timestamp, String nonce, String signature) {
        checkAppIdHasSet();
        boolean check = SERVICE.checkSignature(timestamp, nonce, signature);
        return check;
    }

    /**
     * 向指定用户发送客服文本消息
     * @param toUserOpenId
     * @param content
     * @return
     */
    public static WechatApiResult sendText(String  toUserOpenId, String content) {
        checkAppIdHasSet();
        WxMaKefuMessage msg = new WxMaKefuMessage();
        msg.setToUser(toUserOpenId);
        msg.setMsgType(WxConsts.KefuMsgType.TEXT);
        msg.setText(new WxMaKefuMessage.KfText(content));
        try {
            return new WechatApiResult().setData(SERVICE.getMsgService().sendKefuMsg(msg));
        } catch (WxErrorException e) {
            e.printStackTrace();
            return new WechatApiResult("发送客服消息失败", e);
        }
    }



    private static void checkAppIdHasSet() {
        if (getCurrentAppId() == null) {
            throw new RuntimeException("未设置小程序AppId，请先调用switchTo");
        }
    }

    /**
     * 获取当前处理的appId
     * @return
     */
    public static String getCurrentAppId() {
        return WxMaConfigHolder.get();
    }


}
